package com.shiikong_memory.yez.Arknights.ArknightsData;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.shiikong_memory.yez.MySQLAPI.JavaBean.LotteryDataBean;
import lombok.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class LotteryData {
    @Getter
    private Long AllSize = 0L;
    private Map<String, JSONArray> PoolMap;

    private Map<String, Pool> Pools;

    private static DateFormat DF = new SimpleDateFormat("yyyy-MM-dd");

    @Getter
    @Setter
    private Long Ts;

    public LotteryData(JSONArray jsonArray){
        AllSize += jsonArray.size();
        this.Ts = jsonArray.getJSONObject(0).getLong("ts");
        sortPool(jsonArray);
        Pools = new HashMap<>();
        for (Map.Entry<String, JSONArray> PoolData:PoolMap.entrySet()){
            Pool pool = new Pool(PoolData.getKey(), PoolData.getValue());
            Pools.put(PoolData.getKey(), pool);
        }
    }

    public LotteryData(LotteryDataBean lotteryDataBean){
        this.Ts = lotteryDataBean.getTs();
        Pools = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(lotteryDataBean.getData());
        for (String key:jsonObject.keySet()){
            Pools.put(key, jsonObject.getObject(key, Pool.class));
        }
        AllSize = lotteryDataBean.getSize();
    }

    public void addData(JSONArray jsonArray){
        if (jsonArray.isEmpty()) return;
        AllSize += jsonArray.size();
        this.Ts = jsonArray.getJSONObject(0).getLong("ts");
        sortPool(jsonArray);
        for (Map.Entry<String, JSONArray> PoolData:PoolMap.entrySet()){
            if (Pools.containsKey(PoolData.getKey())){
                Pool pool = Pools.get(PoolData.getKey());
                pool.addData(PoolData.getValue());
            }else {
                Pool pool = new Pool(PoolData.getKey(), PoolData.getValue());
                Pools.put(PoolData.getKey(), pool);
            }
        }
    }

    public void sortPool(JSONArray jsonArray){
        PoolMap = new HashMap<>();
        for (int i=jsonArray.size()-1;i>=0;i--){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("pool");
            if (PoolMap.containsKey(name)){
                PoolMap.get(name).add(jsonObject);
            }else {
                JSONArray array = new JSONArray();
                array.add(jsonObject);
                PoolMap.put(name, array);
            }
        }
    }

    public String getJson(){
        return JSONObject.toJSONString(Pools);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Pool{
        private String name;
        private Integer AllSize = 0;
        private Integer Size = 0;
        private List<Rarity6> rarity6List;

        public Pool(String name, JSONArray array) {
            this.name = name;
            rarity6List = new ArrayList<>();
            for (int i = 0;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                JSONArray objs = jsonObject.getJSONArray("chars");
                for (int j=0;j<objs.size();j++){
                    AllSize++;
                    Size++;
                    JSONObject obj = objs.getJSONObject(j);
                    if (obj.getInteger("rarity") == 5) {
                        rarity6List.add(new Rarity6(LotteryData.DF.format(new Date(jsonObject.getLong("ts")*1000L)),Size, obj.getString("name"), obj.getBoolean("isNew")));
                        Size = 0;
                    }
                }
            }
        }

        public void addData(JSONArray array){
            for (int i = 0;i<array.size();i++){
                JSONObject jsonObject = array.getJSONObject(i);
                JSONArray objs = jsonObject.getJSONArray("chars");
                for (int j=0;j<objs.size();j++){
                    AllSize++;
                    Size++;
                    JSONObject obj = objs.getJSONObject(j);
                    if (obj.getInteger("rarity") == 5) {
                        rarity6List.add(new Rarity6(LotteryData.DF.format(new Date(jsonObject.getLong("ts")*1000L)),Size, obj.getString("name"), obj.getBoolean("isNew")));
                        Size = 0;
                    }
                }
            }
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Rarity6{
        private String time;
        private Integer size;
        private String name;
        private boolean New;
    }

    public String getKMarkdown(){
        StringBuffer jsonData = new StringBuffer();
        for (Map.Entry<String, Pool> poolEntry:Pools.entrySet()){
            StringBuilder data = new StringBuilder();
            Pool value = poolEntry.getValue();
            List<Rarity6> rarity6List = value.getRarity6List();
            for (int i=rarity6List.size()-1;i>=0;i--){
                Rarity6 rarity6 = rarity6List.get(i);
                data.append(JsonResult.formatted(rarity6.getTime(), (rarity6.getName() + (rarity6.isNew() ? "(新)" : "")), rarity6.getSize()+"抽"));
            }
            int i = value.getSize()<50?2:(value.getSize()-50)*2;
            data = new StringBuilder(JsonData.formatted(value.getSize(), i, data.toString()));
            data = new StringBuilder(JsonTitle.formatted(value.getName(), value.getAllSize(), data.toString()));
            jsonData.append(data);
        }
        return Json.formatted(jsonData);
    }

    private static String JsonTitle = """
            ,
                  {
                    "type": "header",
                    "text": {
                      "type": "plain-text",
                      "content": "%s   卡池共抽：%s"
                    }
                  }%s
                  """;

    private static String JsonData = """
            ,
                  {
                    "type": "section",
                    "accessory": {},
                    "text": {
                      "type": "paragraph",
                      "cols": 3,
                      "fields": [
                        {
                          "type": "kmarkdown",
                          "content": "**目前目前已垫：%s**"
                        },
                        {
                          "type": "kmarkdown",
                          "content": "** 当前概率：%d%% **"
                        },
                        {
                          "type": "kmarkdown",
                          "content": ""
                        }%s
                      ]
                    }
                  }""";

    private static String JsonResult = """
            ,
                                    {
                                      "type": "kmarkdown",
                                      "content": "**%s**"
                                    },
                                    {
                                      "type": "kmarkdown",
                                      "content": "**%s**"
                                    },
                                    {
                                      "type": "kmarkdown",
                                      "content": "%s"
                                    }""";

    private static String Json = """
            [
              {
                "type": "card",
                "size": "lg",
                "theme": "warning",
                "modules": [
                  {
                    "type": "header",
                    "text": {
                      "type": "plain-text",
                      "content": "明日方舟抽卡记录"
                    }
                  },
                  {
                    "type": "divider"
                  }%s
                ]
              }
            ]""";
}
